package com.hmyd.hmyd_android.fragment;

import java.net.SocketTimeoutException;

import org.apache.http.client.CookieStore;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.Base;
import com.hmyd.hmyd_android.ui.MainActivity;
import com.hmyd.hmyd_android.utils.HttpExceptionHandler;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.widget.TextView;

public abstract class BasicFragment extends Fragment {
	private Dialog progressDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	RequestParams pms;

	/**
	 * 发送请求
	 * @param postId      // 唯一标识
	 * @param url		  // 请求地址
	 * @param methodType  // 请求方法类型
	 * @param params	  // 请求参数
	 */
	public void onRequest(final int postId,final String url,final HttpMethod methodType,RequestParams params){
		if (!Utils.isConnectByNet(getActivity()) && !Utils.isConnectByMobile(getActivity()) && !Utils.isConnectByWifi(getActivity())) {
			MyToast.showHMToast(getActivity(), false, getString(R.string.network));
			return;
		}

		if(methodType==null){
			return;
		}

		final HttpUtils http = AppBasic.getHttpUtils();
		if(params==null){
			params = new RequestParams();
		}
		
		pms = params;

		// 如果cookieStore存在   http自动管理cookieStore
		if (AppBasic.cookieStore != null && AppBasic.cookieStore.getCookies().size() > 0) {
			http.configCookieStore(AppBasic.cookieStore);
		}

		// 获取时间戳
		String timestamp = String.valueOf(System.currentTimeMillis() + 
				PreferencesUtils.getLong(getActivity(), PreferencesUtils.TIMEDIFFERENCE));

		params.addHeader("hm-app", "HMA");
		params.addHeader("hm-app-v", Utils.getVersionName(getActivity()));
		params.addHeader("hm-app-m", "Prod");
		params.addHeader("hm-app-c", Utils.getUmengChannel(getActivity()));
		params.addHeader("hm-app-id",AppBasic.mDeviceId);
		params.setHeader("hmyd-app-timestamp", timestamp);

		// 签名信息放入头文件
		final String subString = url.substring(UrlConstant.BASEURL.length());
		if(TextUtils.isEmpty(AppBasic.key) && subString.equals("/app/nommal/v1/str")){
			params.setHeader("hmyd-app-sign", Utils.getSign(getActivity(),subString+timestamp));
		}else if(!TextUtils.isEmpty(AppBasic.key) && !subString.equals("/app/nommal/v1/currentTimeMillis")){
			params.setHeader("hmyd-app-sign", Utils.getSign(getActivity(),subString+timestamp+AppBasic.key));
		}else if(TextUtils.isEmpty(AppBasic.key) && !subString.equals("/app/nommal/v1/currentTimeMillis")){
			return;
		}

		progressDialog = new Dialog(getActivity(),R.style.progress_dialog);
		progressDialog.setContentView(R.layout.dialog_waiting);
		progressDialog.setCancelable(false);
		progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
		TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
		msg.setTextSize(12);
		msg.setText("卖力加载中...");

		http.send(methodType, url, params, new RequestCallBack<String>() {

			/**
			 * 开始请求
			 */
			@Override
			public void onStart() {
				if (getActivity()!=null && !getActivity().isFinishing()) {
					progressDialog.show();
				}
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {

			}

			/**
			 * 请求成功
			 */
			 @Override
			 public void onSuccess(ResponseInfo<String> responseInfo) {
				 if (progressDialog.isShowing()) {
					 progressDialog.cancel();
				 }

				 DefaultHttpClient dh = (DefaultHttpClient) http.getHttpClient();
				 if((UrlConstant.LOGIN_SHORT_URL.equals(subString) ||  UrlConstant.REGISTER_SHORT_URL.equals(subString))
						 && dh.getCookieStore()!=null 
						 && dh.getCookieStore().getCookies().size()>0){
					 AppBasic.cookieStore = (CookieStore) dh.getCookieStore();
				 }else{
					 Utils.printOutToConsole(postId+"----"+url);
				 }


				 if(responseInfo.getFirstHeader("server-time")!=null && responseInfo.getFirstHeader("server-time").getValue()!=null){
					 AppBasic.ServerTime = Long.valueOf(responseInfo.getFirstHeader("server-time").getValue());
				 }

				 onPostSuccess(postId,responseInfo.result);
			 }

			 /**
			  * 请求失败
			  */
			 @Override
			 public void onFailure(HttpException error, String msg) {
				 if (getActivity()!=null && !getActivity().isFinishing()) {
					 progressDialog.dismiss();
				 }
				 
				 if (error.getCause() instanceof SocketTimeoutException || error.getCause() instanceof ConnectTimeoutException) {
					 error.getCause().printStackTrace();
					 showErrorDailog(postId, url, methodType, pms);
				 } 
				 
				 try {

					 onPostFailure(postId, msg);

					 if(!TextUtils.isEmpty(msg)){
						 Gson gson = new Gson();
						 java.lang.reflect.Type type = new TypeToken<Base>() {}.getType();
						 Base base = gson.fromJson(msg, type);
						 if(base!=null && base.error!=null){
							 MyToast.showHMToast(getActivity(), false, base.error.message);
							 HttpExceptionHandler.exceptionHandler(getActivity(), base.error.code);
						 }
					 }
				 } catch (JsonSyntaxException e) {
					 e.printStackTrace();
				 }
			 }
		});
	}

	/**
	 * 请求成功
	 * @param postId
	 * @param msg
	 */
	public abstract void onPostSuccess(int postId,String msg);

	/**
	 * 请求失败
	 * @param postId
	 * @param msg
	 */
	public abstract void onPostFailure(int postId,String msg);
	
	// 弹出错误提示框
	public void showErrorDailog(final int postId,final String url,final HttpMethod methodType,final RequestParams params) {
		final NormalDialog cd = new NormalDialog(getActivity(),
				R.style.calculatorDialog, new NormalDialogListener() {
			@Override
			public void ok() {
				reConnect(postId, url, methodType, params);
			}

			@Override
			public void cancle() {
				AppBasic.getInstance().exitSystem();
			}

			@Override
			public void closed() {
				AppBasic.getInstance().exitSystem();
			}

		}, getString(R.string.alert),
		getString(R.string.timeout),
		getString(R.string.rerequest),
		getString(R.string.exit));

		if(null != cd){
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					cd.show();
				}
			});
		}
	}

	/**
	 * 请求超时，重建加密通道
	 */
	private void reConnect(int postId,String url,HttpMethod methodType,RequestParams params){
		onRequest(postId, url, methodType, params);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	/*@Override
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	public static View rootView;

	@Override
	public void onDestroyView() {

		if (rootView != null && rootView.getParent() != null) {
			((ViewGroup)rootView.getParent()).removeView(rootView);
		}
		if (this != null) {
			FragmentManager mManager = getFragmentManager();
			if(mManager != null && !mManager.isDestroyed()){
				final FragmentTransaction mTransaction = mManager.beginTransaction();
				if(mTransaction != null){
					mTransaction.remove(this).commit();
				}
			}
		}
	}*/

}
